/**
 * @file   照片配置
 * @author 李刚
 * @date 2021-09-25 15:24:11
 */

layui.define(['element', 'layer', 'form', 'table', 'zmnSelect', 'zmnOmsSelect', 'laytpl', '$http',], function (exports) {
    let $ = layui.$;
    let form = layui.form;
    let $http = layui.$http;
    let layer = layui.layer;
    let zmnSelect = layui.zmnSelect;
    let zmnOmsSelect = layui.zmnOmsSelect;
    var table = layui.table;
    let CONF_BASE_URL = OMS_BASE_URL + '/conf/attachment/orderPicture';


    /**
     * 获取某个元素下子元素的文本值
     * @param item
     * @param ele
     * @returns {jQuery}
     */
    function getText(item, ele) {
        return $(item).find(ele).text() || $(item).find(ele).val();
    }

    /**
     * 判断是否是正整数
     * @param val {number/string} 字符串或数字
     * @returns {boolean} 返回是否是数字
     */
    function isNumber(val) {
        var reg = /^[0-9]\d*$/;//正整数
        return reg.test(val);
    }

    /**
     * 打开对话框
     * @param {Object} config 配置
     */
    function openDialog (config) {
        let defaultConfig = {
            type: 2,
            content: '/',
            title: '',
            shade: [0.8, '#393D49'],
            area: ['40%', '750px'],
            minWidth: '600px',
            zIndex: layer.zIndex, // 重点1
            success: function(layero) {
                parent.layer.setTop(layero); // 重点2
            },
            end: function(index, layero){
                // 刷新列表
                if(config.reload){
                    table.reload("conf-table", {}, true);
                }
            }
        };
        parent.layer.open(Object.assign({}, defaultConfig, config));
    }

    /**
     * 获取查询参数
     * @param field
     * @returns {{}}
     */
    function getSearchParams(field) {
        let params = {};
        if (field) {
            // 拷贝非空字段
            Object.keys(field).filter((key) => {
                params[key] = field[key];
            });
        }
        return params;
    }

    /**
     * 渲染表格
     * @param {object} params 查询参数
     * @returns {object}
     */
    function renderTable() {
        table.render({
            elem: '#conf-table',
            url: CONF_BASE_URL + '/ajax/list.action',
            where: getSearchParams(),
            toolbar: '#toolbar',
            defaultToolbar: ['filter', 'exports', 'print'],
            page: true,
            cols: [[
                {field: 'sort', title: '排序', width: 60, templet: "#sortInput"},
                {field: 'id', title: 'ID', width: 60, unresize: true, sort: true},
                {field: 'categName', title: '照片类型'},
                {field: 'channelNames', title: '应用渠道', templet: (d) => !d.channelNames && !d.excludeChannelNames ? "全渠道"
                        : (!d.channelNames ? "" : d.channelNames)},
                {field: 'excludeChannelNames', title: '排除渠道'},
                {field: 'rephotograph', title: '允许删除',templet: (d)=>d.rephotograph?"是":"否"},
                {field: 'bizTypeName', title: '应用业务类型'},
                {field: 'orderDetailShow', title: '订单详情',templet: (d)=>d.orderDetailShow?"展示":"不展示"},
                {field: 'servCategNames', title: '服务分类'},
                {field: 'num', title: '照片张数', width: 60},
                {field: 'needReview', title: '后台审核',templet: '#switchNeedReviewTpl', unresize: true, width: 80},
                {field: 'mustUpload', title: '必传', templet: '#switchMustUploadTpl', unresize: true, width: 80},
                {field: 'auditStandardStatusName', title: '审核标准',width: 60},
                {field: 'autoAudit', title: '自动审核', templet: '#switchAutoAuditTpl', unresize: true, width: 80},
                {field: 'egSrc', title: '示例照片', templet: '#showTpl', unresize: true, width: 60},
                {field: 'creater', title: '最近操作人/时间', width: 200, templet: function (res) {
                    if (res.updater) {
                        return res.updater + '/' + res.updateTime;
                    } else {
                        return res.creater + '/' + res.createTime;
                    }
                }},
                {fixed: 'right', title: '操作', toolbar: '#editTpl', width: 200},
            ]],
            request: {
                pageName: 'pageIndex', // 页码
                limitName: 'pageSize' // 条数限制
            },
            response: {
                statusCode: 200 // 重新规定成功的状态码为 200，table 组件默认为 0
            },
            parseData: function (res) { //将原始数据解析成 table 组件所规定的数据
                var count = res.data ? res.data.count : 0;
                $('.layui-this').find('.count').text('（共 ' + count + ' 条）');
                return {
                    "code": res.status,
                    "msg": res.message,
                    "count": res.data ? (res.data.count > 10000 ? 10000 : res.data.count) : 0, //解析数据长度
                    "data": res.data ? res.data.data : [] //解析数据列表
                };
            },
            done:initTableEvent
        });
    }

    function initTableEvent() {
        // 监听修改排序
        $('.sort').blur(function (event) {
            let sort = $(this).val();
            if (!isNumber(sort)) {
                layer.msg("请输入正整数");
                return;
            }

            let id = getText($(this).parents("tr"), 'td[data-field=id]');
            let url = CONF_BASE_URL + '/modifySort.action';
            $http.$get(url, {id: id, sort: sort}).then(function () {
                layer.msg('操作成功', { icon: 1, time: 1000 });
            }, (msg) => {
                layer.msg(msg);
            });
        });
    }

    function initEvent() {
        // 监听重置按钮点击
        form.on('submit(submit-reset)', function (obj) {
            let zmnFields = ['categIds', 'channelIds', 'bizType', 'servCategIds'];
            zmnFields.forEach(e => zmnOmsSelect.clearSelectedData(e));
            $('select').val('');
            form.render('select');
            return false;
        });

        // 头工具栏事件
        table.on('toolbar(conf-table)', function (obj) {
            switch (obj.event) {
                case 'add':
                    top.layui.index.openTabsPage(CONF_BASE_URL + '/addEdit.action', "新增");
                    break;
            }
        });

        // 监听行工具事件
        table.on('tool(conf-table)', function (obj) {
            if (obj.event === 'edit') {
                top.layui.index.openTabsPage(CONF_BASE_URL + '/addEdit.action?id=' + obj.data.id, "详情");
            }
            if (obj.event === 'auto') {

                openDialog({
                    type: 2,
                    title: '设置审核标准',
                    area: ['650px', '600px'],
                    content: CONF_BASE_URL + '/auditStandard.action?id=' + obj.data.id,
                    reload:true
                })
            }
            if (obj.event === 'del') {
                let url = CONF_BASE_URL + '/delete.action';
                layer.confirm("您确定要删除吗？", {title: "提醒"}, function (index) {
                    layer.close(index);
                    $http.$get(url, {id: obj.data.id}).then(function () {
                        layer.msg('操作成功', {icon: 1, time: 1000});
                        obj.del();
                    }, (msg) => {
                        layer.msg(msg);
                    });
                });
            }
            if (obj.event === 'show') {
                let imgHtml = "<img src='" +  obj.data.egSrc + "' width='100%' height='100%'/>";
                openDialog({
                    type: 1,
                    shade: 0.8,
                    offset: 'auto',
                    area: [600 + 'px',300+'px'],
                    shadeClose:true,
                    scrollbar: false,
                    title: "", //不显示标题
                    content: imgHtml, //捕获的元素，注意：最好该指定的元素要存放在body最外层，否则可能被其它的相对元素所影响
                    reload:false
                })
            }
        });

        // 监听状态操作
        form.on('switch(needReview)', function (obj) {
            let url = CONF_BASE_URL + '/modifyNeedReview.action';
            $http.$get(url, {id: this.value, needReview: obj.elem.checked ? 2 : 1}).then(function () {
                layer.msg('操作成功', {icon: 1, time: 1000});
            }, (msg) => {
                obj.othis.parent().find(':checkbox').prop("checked", !obj.elem.checked);
                form.render('checkbox');
                layer.msg(msg);
            });
        });

        form.on('switch(autoAudit)', function (obj) {
            let url = CONF_BASE_URL + '/modifyAutoAudit.action';
            $http.$get(url, {id: this.value, autoAudit: obj.elem.checked ? 2 : 1}).then(function () {
                layer.msg('操作成功', {icon: 1, time: 1000});
            }, (msg) => {
                obj.othis.parent().find(':checkbox').prop("checked", !obj.elem.checked);
                form.render('checkbox');
                layer.msg(msg);
            });
        });

        form.on('switch(mustUpload)', function (obj) {
            let url = CONF_BASE_URL + '/modifyMustUpload.action';
            $http.$get(url, {id: this.value, mustUpload: obj.elem.checked ? 2 : 1}).then(function () {
                layer.msg('操作成功', {icon: 1, time: 1000});
            }, (msg) => {
                obj.othis.parent().find(':checkbox').prop("checked", !obj.elem.checked);
                form.render('checkbox');
                layer.msg(msg);
            });
        });

        // 查询
        form.on('submit(submit-search)', function (obj) {
            table.reload("conf-table", {
                where: getSearchParams(obj.field),
                page: {
                    curr: 1 //重新从第 1 页开始
                }
            });
            return false;
        });
    }

    /**
     * 初始化下拉框
     */
    function initSelect(){
        zmnSelect.selectlServBizUnits({
            bizTypeSelectId: 'bizType',
            // bizLineSelectId: 'bizLine',
        }, null);

        zmnOmsSelect.selectConfOrderAttachmentCategory('categIds', {
            tips: "全部",   //默认提示
            type: 1,
            page: {
                enable: true,
                remote:true,
                pageSize: 20
            },
        });

        // 应用渠道
        zmnSelect.searchChannel('channelIds', {
            remote: {
                events: {
                    extendParams: function () {
                        return {
                            "rank": 2, //渠道层级：Integer类型；1-查询一级渠道，2-查询二级渠道,null不限
                        }
                    }
                }
            },
            events: {
                changed: function (values) {
                }
            }
        });
       // 服务分类
       zmnSelect.selectServCategory('servCategIds', null)
    }

    function init() {
        initEvent();
        renderTable();
        initTableEvent();
        initSelect();
    }

    init();
    exports('oms_conf_attachment_orderPicture_list');
});
